<template>
  <div class="table">
    <div class="table-form" v-if="showSearch">
      <vxForm ref="formRef" :formItems="formItems" :formData="formData">
        <template v-slot:button>
          <el-col :span="formItems.span">
            <el-button type="primary" @click="searchTable">{{
              $t(lang.search)
            }}</el-button>
            <el-button type="info" @click="resetSeach">{{
              $t(lang.reset)
            }}</el-button>
          </el-col>
        </template>
      </vxForm>
    </div>
    <div class="table-buttons">
      <div>
        <slot name="tableButton"></slot>
      </div>
      <div class="table-opicon" v-if="tableConfig.opIcon">
        <el-button circle @click="renovateTable" :icon="Refresh" />
        <el-button circle @click="swichColumn" :icon="Operation" />
        <el-button circle @click="swichSearch" :icon="Search" />
      </div>
    </div>
    <vxe-table
      class="mytable-scrollbar"
      ref="xTable"
      :loading="data.loading"
      border
      show-header-overflow
      show-overflow
      keep-source
      :max-height="tableConfig.maxHeight"
      :stripe="tableConfig.stripe"
      :size="tableConfig.size"
      :align="tableConfig.align"
      :round="tableConfig.round"
      :row-class-name="tableConfig.rowClassName"
      :cell-class-name="tableConfig.cellClassName"
      :empty-text="tableConfig.emptyText"
      :column-config="tableConfig.columnConfig"
      :row-config="{ isHover: true }"
      :area-config="tableConfig.areaConfig"
      :checkbox-config="tableConfig.checkboxConfig"
      :resizable-config="tableConfig.resizableConfig"
      :seq-config="tableConfig.seqConfig"
      :sort-config="tableConfig.sortConfig"
      :filter-config="tableConfig.filterConfig"
      :expand-config="tableConfig.expandConfig"
      :import-config="tableConfig.importConfig"
      :print-config="tableConfig.printConfig"
      :radio-config="tableConfig.radioConfig"
      :tooltip-config="tableConfig.tooltipConfig"
      :tree-config="tableConfig.treeConfig"
      :menu-config="tableConfig.menuConfig"
      :mouse-config="tableConfig.mouseConfig"
      :keyboard-config="tableConfig.keyboardConfig"
      :edit-config="tableConfig.editConfig"
      :valid-config="tableConfig.validConfig"
      :edit-rules="validRules"
      :loading-config="tableConfig.loadingConfig"
      :custom-config="tableConfig.customConfig"
      :data="data.tableData"
      @cell-click="cellClickEvent"
      @radio-change="radioChangeEvent"
      @checkbox-all="selectAllChangeEvent"
      @checkbox-change="selectChangeEvent"
    >
      <span v-for="(op, index) in column">
        <vxe-column
          v-if="op.visible"
          :key="index"
          :type="op.type"
          :field="op.field"
          :align="op.align"
          :fixed="op.fixed"
          :title="op.title"
          :min-width="op.minWidth"
          :width="op.width"
          :filters="op.filters"
          :filter-method="op.filterMethod"
          :filter-multiple="op.filtermultiple"
          :filter-reset-method="op.filterResetMethod"
          :filter-recover-method="op.filterRecoverMethod"
          :filter-render="op.filterRender"
          :export-method="op.exportMethod"
          :title-prefix="op.titlePrefix"
          :class-name="op.className"
          :header-class-name="op.headerClassName"
          :formatter="op.formatter"
          :sortable="op.sortable"
          :sort-by="op.sortBy"
          :cell-render="op.cellRender"
          :edit-render="op.editRender"
          :content-render="op.contentRender"
          :tree-node="op.treeNode"
          :footer-method="op.footerMethod"
          :footer-cell-class-name="op.footerCellClassName"
        >
          <template #header v-if="op.type == 'radio'">
            <vxe-button
              type="text"
              @click="clearRadioRowEevnt"
              :disabled="!data.selectRow"
              >取消</vxe-button
            >
          </template>
          <template
            #edit="{ row, scope }"
            v-if="op.inputType == 'input' && tableConfig.isEdit"
          >
            <vxe-input
              v-model="row[op.field]"
              type="text"
              @change="$refs.xTable.updateStatus(scope)"
              :placeholder="op.placeholder"
            ></vxe-input>
          </template>
          <template
            #edit="{ row, scope }"
            v-if="op.inputType == 'select' && tableConfig.isEdit"
          >
            <vxe-select
              v-model="row[op.field]"
              type="text"
              @change="$refs.xTable.updateStatus(scope)"
              :options="op.options"
              transfer
              :placeholder="op.placeholder"
            ></vxe-select>
          </template>
          <template
            #edit="{ row, scope }"
            v-if="op.inputType == 'date' && tableConfig.isEdit"
          >
            <vxe-input
              v-model="row[op.field]"
              @change="$refs.xTable.updateStatus(scope)"
              type="date"
              :placeholder="op.placeholder"
              transfer
            ></vxe-input>
          </template>
        </vxe-column>
      </span>
      <vxe-column
        fixed="right"
        title="操作"
        width="240"
        v-if="tableConfig.operate"
      >
        <template #default="{ row }">
          <span v-for="(btn, i) in operates">
            <vxe-button
              v-if="btn.view.indexOf(row[btn.target]) === -1"
              :key="i"
              type="text"
              :icon="btn.icon"
              :status="btn.status"
              :content="btn.btnName"
              @click="btnEvent(row, btn)"
            ></vxe-button>
          </span>
        </template>
      </vxe-column>
      <template
        #empty
        v-if="!tableConfig.emptyText || tableConfig.emptyText == ''"
      >
        <span>
          <img width="400" src="@/assets/empty.png" />
        </span>
      </template>
    </vxe-table>
    <vxe-pager
      background
      v-model:current-page="pages.pageNo"
      v-model:page-size="pages.pageSize"
      :total="pages.totalResult"
      @page-change="changePages"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'JumpNumber',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total',
      ]"
    >
    </vxe-pager>
  </div>
  <Setting ref="setting" :tableOption="tableOption"></Setting>
</template>

<script setup lang="ts">
import {
  VXETable,
  VxeTableInstance,
  VxeColumnProps,
  VxeTableProps,
  VxeTableEvents,
  VxePagerEvents,
  VxeTablePropTypes,
} from "vxe-table";
import { Refresh, Operation, Search } from "@element-plus/icons-vue";
import { getTable } from "@/api/menu";
import Setting from "./setting.vue";
import vxForm from "@/components/vx-form/index.vue";
import handleColumn from "./tableHooks";
import { ElMessage } from "element-plus";
import { inject } from "vue";
const lang: any = reactive(inject("langs"));
let props = defineProps({
  tableOption: {
    type: Object,
    required: true,
    default: {},
  },
});
let { columns } = handleColumn(props.tableOption.column);
const setting = ref();
const emit = defineEmits([
  "btnEvent",
  "radioChangeEvent",
  "selectAllChangeEvent",
  "selectChangeEvent",
]);
// let column = reactive<VxeColumnProps | any>(props.tableOption.column);
let column = columns;
let tableConfig = reactive<VxeTableProps | any>(props.tableOption.table);
let operates = reactive(props.tableOption.operates);
const xTable = ref<VxeTableInstance>();
const data = ref({
  loading: false,
  tableData: [] as any[],
  selectRow: null as any,
});
let pages = reactive({
  pageNo: 1,
  pageSize: 10,
  totalResult: 0,
});
interface formDataType {
  pageNo: number;
  pageSize: number;
}
let URL = ref();
let OBJ = ref();
const formRef = ref();
const validRules = ref<VxeTablePropTypes.EditRules>(
  props.tableOption.validRules
);
let formData = reactive<any>({});
let formItems = props.tableOption.form;
let showSearch = ref(true);
const getTableList = async (url: string, method: string, obj?: Object) => {
  URL.value = url;
  OBJ.value = obj;
  data.value.loading = true;
  (formData.pageNo = pages.pageNo), (formData.pageSize = pages.pageSize);
  let objs = Object.assign(formData, obj);
  try{
    const res = await getTable(url, method, objs)
    // if(res.code == 200){
      data.value.tableData = res.data;
      pages.totalResult = res.total;
      pages.pageNo = res.pageNo;
      data.value.loading = false;
    // }
  } catch (err) {
    console.log(err)
  }
};
const searchTable = () => {
  if (!URL.value || URL.value == "") {
    ElMessage({
      showClose: true,
      message: "未找到请求接口",
      type: "error",
    });
    return;
  }
  (pages.pageNo = 1), (pages.pageSize = 10);
  pages.totalResult = 0;
  getTableList(URL.value, "post", OBJ.value);
};
const resetSeach = () => {
  (pages.pageNo = 1), (pages.pageSize = 10);
  pages.totalResult = 0;
  formData = reactive<any>({});
  formRef.value.resetForm();
  getTableList(URL.value, "post", OBJ.value);
};
//表格分页事件
const changePages: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
  console.log(currentPage, pageSize);
  pages.pageNo = currentPage;
  pages.pageSize = pageSize;
  getTableList(URL.value, "post");
};
//单元格点击事件
const cellClickEvent: VxeTableEvents.CellClick = () => {
  console.log("单元格点击事件");
};
//单元框选中
const radioChangeEvent: VxeTableEvents.RadioChange = ({ row }) => {
  data.value.selectRow = row;
  emit("radioChangeEvent", data.value.selectRow);
  // console.log("单选事件", data.selectRow);
};
//取消单选框选中状态
const clearRadioRowEevnt = () => {
  let $table = xTable.value;
  data.value.selectRow = null;
  $table?.clearRadioRow();
};
//复选框全选事件
const selectAllChangeEvent: VxeTableEvents.CheckboxAll = ({ checked }) => {
  const $table = xTable.value;
  const records = $table?.getCheckboxRecords();
  data.value.selectRow = checked ? checked : records;
  emit("selectAllChangeEvent", data.value.selectRow);
};
//复选框选中事件
const selectChangeEvent: VxeTableEvents.CheckboxChange = ({ checked }) => {
  const $table = xTable.value;
  const records = $table?.getCheckboxRecords();
  data.value.selectRow = checked ? checked : records;
  emit("selectChangeEvent", data.value.selectRow);
};
// 操作按钮点击事件
const btnEvent = (row: any, btn: any) => {
  // console.log(row, btn);
  emit("btnEvent", row, btn);
};
//插入表格
const insertEvent = async () => {
  const $table = xTable.value;
  const newRecord = {};
  const { row: newRow } = await $table!.insert(newRecord);
  await $table?.setEditRow(newRow);
};
//删除表格
const removeSelectEvent = async () => {
  const $table = xTable.value;
  await $table?.removeCheckboxRow();
};
//保存表格
const saveEvent = async () => {
  const $table = xTable.value;
  const { insertRecords, removeRecords, updateRecords } =
    $table!.getRecordset();
  if (
    insertRecords.length <= 0 &&
    removeRecords.length <= 0 &&
    updateRecords.length <= 0
  ) {
    VXETable.modal.message({ content: "数据未改动！", status: "warning" });
    return;
  }
  const errMap = await $table?.validate();
  if (errMap) {
    return;
  }
  const body = { insertRecords, removeRecords, updateRecords };
};
onMounted(() => {
  // getTableList(URL.value);
});
const renovateTable = () => {
  getTableList(URL.value, "post", OBJ.value);
};
const swichColumn = () => {
  setting.value.dialogData.dialogVisible = true;
};
const swichSearch = () => {
  showSearch.value = !showSearch.value;
};
defineExpose({
  insertEvent,
  removeSelectEvent,
  saveEvent,
  data,
  getTableList,
  btnEvent,
  selectAllChangeEvent,
  selectChangeEvent,
  radioChangeEvent,
});
</script>

<style lang="scss">
/*滚动条整体部分*/
.mytable-scrollbar ::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
/*滚动条的轨道*/
.mytable-scrollbar ::-webkit-scrollbar-track {
  background-color: #ffffff;
}
/*滚动条里面的小方块，能向上向下移动*/
.mytable-scrollbar ::-webkit-scrollbar-thumb {
  background-color: #bfbfbf;
  border-radius: 5px;
  border: 1px solid #f1f1f1;
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}
.mytable-scrollbar ::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}
.mytable-scrollbar ::-webkit-scrollbar-thumb:active {
  background-color: #787878;
}
/*边角，即两个滚动条的交汇处*/
.mytable-scrollbar ::-webkit-scrollbar-corner {
  background-color: #ffffff;
}
.mytable-scrollbar {
  width: auto;
}
.table {
  width: 100%;
  display: block;
  &-opicon {
    .icon {
      font-size: 22px;
      color: var(--ep-color-primary);
      margin-right: 10px;
      cursor: pointer;
    }
  }
  &-form {
    width: 100%;
    transition: all 1s;
    &--button {
      width: 100%;
      text-align: center;
    }
  }
  &-buttons {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
  }
}
</style>
